package com.ndphu.comic.gui.fragment.book;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.ndphu.comic.R;
import com.ndphu.comic.db.DatabaseHelper;
import com.ndphu.comic.io.extend.AsyncTask;

public class OnlinePageFragment extends Fragment {

	private static final String TAG = OnlinePageFragment.class.getSimpleName();

	private static final int MAX_SIZE = 4096;
	private String mPageUrl;
	private int mScreenHeight;
	private int mScreenWidth;
	private LinearLayout mContainter;
	private AsyncTask<String, Void, Bitmap> asyncTask;
	private PagerAdapter mPagerAdapter;
	private ProgressBar mProgressBar;
	private boolean running = true;

	private DatabaseHelper db;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		mScreenHeight = displaymetrics.heightPixels;
		mScreenWidth = displaymetrics.widthPixels;
		View view = inflater.inflate(R.layout.fragment_online_book_page, container, false);
		this.mContainter = (LinearLayout) view.findViewById(R.id.container);
		mProgressBar = (ProgressBar) view.findViewById(R.id.fragment_online_book_page_progress);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (mPageUrl == null) {
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (running) {
					try {
						if (db != null) {
							byte[] cachedData = db.getCachedPage(mPageUrl);
							if (cachedData != null) {
								Log.d(TAG, String.format("Cache hit, data size = %d", cachedData.length));
								renderContent(cachedData);
								break;
							}
						}
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	@Override
	public void onDestroyView() {
		Log.d(TAG, "On destroy view");
		this.running = false;
		super.onDestroyView();
	}

	public static interface BitmapLoadedListener {
		void onBitmapLoaded(String url, Bitmap bm);
	}

	@Override
	public void onDestroy() {
		if (asyncTask != null) {
			asyncTask.cancel(true);
		}
		super.onDestroy();
	}

	private void renderContent(byte[] raw) {
		renderContent(BitmapFactory.decodeByteArray(raw, 0, raw.length), true);
	}

	private void renderContent(final Bitmap content, boolean strecth) {
		if (this == null || this.getActivity() == null) {
			return;
		}
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				mProgressBar.setVisibility(View.GONE);
				mContainter.removeAllViews();
				getPagerAdapter().notifyDataSetChanged();
			}
		});
		if (content == null) {
			final ImageView iv = new ImageView(this.getActivity());
			iv.setScaleType(ScaleType.FIT_CENTER);
			iv.setImageResource(R.drawable.ic_error_page_not_found);
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mContainter.addView(iv);
					getPagerAdapter().notifyDataSetChanged();
				}
			});
		} else {
			int max = content.getWidth() > content.getHeight() ? content.getWidth() : content.getHeight();
			if (max < 4096) {
				final ImageView iv = new ImageView(this.getActivity());
				if (strecth) {
					final Bitmap scaled = Bitmap.createScaledBitmap(content, mScreenWidth, mScreenHeight, false);
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							iv.setImageBitmap(scaled);
							mContainter.addView(iv);
							getPagerAdapter().notifyDataSetChanged();
						}
					});
				} else {
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							iv.setScaleType(ScaleType.FIT_CENTER);
							iv.setImageBitmap(content);
							mContainter.addView(iv);
							getPagerAdapter().notifyDataSetChanged();
						}
					});
				}
			} else {
				if (max == content.getHeight()) {
					int time = max / MAX_SIZE;
					int i = 0;
					for (; i < time; ++i) {
						final Bitmap subBitmap = Bitmap.createBitmap(content, 0, i * MAX_SIZE, content.getWidth(),
								MAX_SIZE);
						final ImageView iv = new ImageView(this.getActivity());
						getActivity().runOnUiThread(new Runnable() {

							@Override
							public void run() {
								iv.setScaleType(ScaleType.FIT_CENTER);
								iv.setImageBitmap(subBitmap);
								mContainter.addView(iv);
								getPagerAdapter().notifyDataSetChanged();
							}
						});
					}
					final Bitmap subBitmap = Bitmap.createBitmap(content, 0, time * MAX_SIZE, content.getWidth(), max
							% MAX_SIZE);
					final ImageView iv = new ImageView(this.getActivity());
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							iv.setScaleType(ScaleType.FIT_CENTER);
							iv.setImageBitmap(subBitmap);
							mContainter.addView(iv);
							getPagerAdapter().notifyDataSetChanged();
						}
					});
				}
			}
		}
	}

	public String getUrl() {
		return mPageUrl;
	}

	public void setUrl(String url) {
		this.mPageUrl = url;
	}

	public PagerAdapter getPagerAdapter() {
		return mPagerAdapter;
	}

	public void setPagerAdapter(PagerAdapter mPagerAdapter) {
		this.mPagerAdapter = mPagerAdapter;
	}

	public void setDatabaseProvider(DatabaseHelper db) {
		this.db = db;
	}
}
